package proto;

import javafx.async.Task;
import java.lang.UnsupportedOperationException;
import javafx.util.Math;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Rectangle;
import javafx.scene.input.MouseEvent;

public class TaskExecutor extends Task {

       def executor    :
                        TaskExecutorImpl
                       =  TaskExecutorImpl {

        };


    public var task: function();
    public var onTaskDone: function(result: Object);

    init {
        executor.setTask(task);
        executor.setTaskCompletionHandler(onTaskDone);
    }

    override public function stop(): Void {
        stopped = true;
        started = false;
        executor.signalInterrupt();
    }

    override public function start(): Void {
        if (task != null and not(started)) {
            started = true;
            stopped = false;
            executor.run();
        }
    }

}

public function fib(n:Number):Number {
    if (n <= 1) return n;
    return fib(n-1) + fib(n-2);
}

function run() {
    var exec:TaskExecutor = TaskExecutor {
                task: function () {
                    for (i in [0..150])
                        for (j in [0..100]) {
                                if(exec.stopped != true)
                                  println ("{fib(i * j)} ")
                                else return;
                        }
                }
            }
    exec.onTaskDone = function (e) {
        println("Got back {e}");
    }

    Stage {
        title: "MyApp"
        scene: Scene {
            width: 200
            height: 200
            content: [
                Circle { centerX: 20 centerY: 20 radius: 20
                    onMousePressed:function(e:MouseEvent){
                        println ("Start exec");
                        exec.start();
                    }

                }
                Rectangle { x: 40 y: 20 width: 50 height: 20
                    onMousePressed:function(e:MouseEvent){
                        exec.stop();
                    }

                }
            ]
        }
    }
}
